#include <iostream>
using namespace std;
struct Node {
	int val;
	Node* next;
	Node(int _val): val(_val), next(nullptr) {}
};
Node* reverseList(Node*, int);
void showList(Node*);
Node* createList(int[], int);
int main() {
	int lValues[5] = {1, 2, 3, 4, 5};
	Node* l = createList(lValues, 5);
	showList(l);
	Node* l2 = reverseList(l, 3);
	showList(l2);
	return 0;
}
Node* reverseList(Node* head, int n) {
    if (n <= 1 || !head) return head;
    Node* prev = nullptr;
    Node* curr = head;
    Node* nextTemp = nullptr;
    for (int i = 0; i < n && curr; ++i) {
        nextTemp = curr->next;
        curr->next = prev;
        prev = curr;
        curr = nextTemp;
    }
    if (nextTemp) head->next = nextTemp;
    return prev;
}
void showList(Node* head) {
	Node* p = head;
	while (p) {
		cout << p->val << ' ';
		p = p->next;
	}
	cout << endl;
}
Node* createList(int values[], int size) {
	Node* ret = new Node(values[0]);
	Node* p = ret;
	for (int i = 1; i < size; ++i) {
		p->next = new Node(values[i]);
		p = p->next;
	}
	return ret;
}
